import Vue from 'vue'
import Vuex from 'vuex'
import { login,validate } from '../src/api/user'
import {setLocal} from  '../util/local'
import router from  './router'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    username: '',   //用户名字
    isShowLoading: false
  },
  mutations: {
    hide_loading(state) {
      state.isShowLoading = false;
    },
    show_loading(state) {
      state.isShowLoading = true;
    },
    set_user(state, payload) {
      state.username = payload
    }
  },
  actions: {
    async   set_user({ commit }, username) {
      let data = await login(username);
      if (data.code !== 0) {
        return Promise.reject(data.data);
      }
      commit('set_user', data.username);
      //将token 储存到服务端
      //请求带上token 校验token  如果不正确或者过期  没登陆
      setLocal('token',data.token);
    },
    async validate({commit}){
      let r = await validate();
      if(r.code === 0){
        commit('set_user',r.username);
        setLocal('token',r.token);
      }
      return r.code === 0;
    }
  }
})
